package com.bosintek.wordtest.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Vector;

import org.w3c.dom.Document;

import com.bosintek.wordtest.Bank;
import com.bosintek.wordtest.WordSet;

public class Parser {
	public Vector<Bank> parseXML(String xml) {
		if(xml.equals("")){
			return new Vector<Bank>();
		}
		Vector <Bank> banks;// = new Vector <Bank>();
		Document doc = XMLfunctions.XMLfromString(xml);
		banks = XMLfunctions.parseBanks(doc);
		return banks;
	}

	public Vector<Bank> parsePlain(InputStream plain){
		Vector <Bank> banks = new Vector <Bank>();
		
		Vector<WordSet> allWsets = new Vector<WordSet>();
		String meaning;
		String word;
		try {
			// The default bank is loaded.
			BufferedReader br = new BufferedReader(new InputStreamReader(
					plain, Charset.forName("ISO-8859-1")));

			String line = br.readLine();
			while (line != null) {
				word = line.substring(0, line.indexOf(" - "));
				meaning = line
						.substring(line.indexOf(" - ") + 3, line.length());
				allWsets.add(new WordSet(word, meaning));
				line = br.readLine();
				while (line != null && line.equals("")) {
					line = br.readLine();
				}
			}
			br.close();

		} catch (Exception e) {
			allWsets.add(new WordSet("NO WORDS LEFT", "NO WORDS LEFT"));
			System.out.println("Error de lectura: " + e.getMessage());
		}
		String bankName = ObjectsManager.getUser()+" bank";
		Bank bank = new Bank();
		bank.setName(bankName);
		bank.setwSets(allWsets);
		banks.add(bank);
		return banks;
		
	}
}
